import 'package:flutter/material.dart';
import 'package:sample2/components/alert_helper.dart';
import 'package:sample2/helper/app_helper.dart';
import 'package:sample2/model/auth/login_info.dart';
import 'package:sample2/pages/login/forget_password.dart';
import 'package:sample2/pages/login/register.dart';
import 'package:sample2/services/user_service.dart';
import 'package:sample2/utils/networking.dart';
import 'package:sample2/utils/string_util.dart';
import "package:crypto/crypto.dart";
import "dart:convert";

typedef LoginCallback = void Function(String);

class LoginPage extends StatefulWidget {
  final LoginCallback? afterLogin;
  const LoginPage({this.afterLogin, super.key});

  @override
  State<StatefulWidget> createState() {
    return LoginState();
  }
}

class LoginState extends State<LoginPage> {
  bool showPwd = false;
  String? username;
  String? password;
  LoginState();
  final TextEditingController _textEditingController = TextEditingController();

  @override
  void initState() {
    AppHelper.shared.getLastLoginName().then((value) {
      if (value != null) {
        username = value;
        _textEditingController.text = value;
      }
    });

    super.initState();
  }

  void onPressed() {
    if (StringUtil.isNullOrEmpty(username)) {
      AlertHelper.showAlert(
          context: context,
          title: "Test2",
          message: "username can not be null");
      return;
    }
    if (StringUtil.isNullOrEmpty(password)) {
      AlertHelper.showAlert(
          context: context,
          title: "Test1",
          message: "password can not be null");
      return;
    }
    
    LoginInfo loginInfo = LoginInfo(username: username!, password: md5.convert(utf8.encode(password!)).toString());
    debugPrint(loginInfo.toParameters().toString());
    UserService.login(loginInfo).then((response) {
      if (response.respondCode == 0) {
        if (widget.afterLogin != null) {
          widget.afterLogin!("2");
        }
      } else {
        AlertHelper.showAlert(context: context, message: response.responseMsg);
      }
    })
    .catchError((error) {
      if(error.runtimeType == NetworkResponseObject){
        NetworkResponseObject resp = error;
        AlertHelper.showAlert(context: context, message: resp.responseMsg ?? "request error");
        return;
      }else{
        AlertHelper.showAlert(context: context, message:error.toString());
      }
      
    });
  }

  void onChangeUserName(String newUserName) {
    username = newUserName;
    debugPrint("got username: ${username!}");
  }

  void onChangePassword(String newPassword) {
    password = newPassword;
    debugPrint("got password: ${password!}");
  }

  void createAccount() {
    Navigator.of(context)
        .push(MaterialPageRoute(builder: (BuildContext context) {
      return const Register();
    }));
  }

  void forgetPassword() {
    Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) {
      return const ForgetPwd();
    }));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.greenAccent,
        body: Center(
            child: SizedBox(
          width: 0.8 * MediaQuery.of(context).size.width,
          child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
            Image.asset("images/logo.jpeg"),
            Padding(
              padding: const EdgeInsets.fromLTRB(0, 10, 0, 0),
              child: TextField(
                controller: _textEditingController,
                autofocus: true,
                onChanged: onChangeUserName,
                decoration: const InputDecoration(
                  icon: Icon(Icons.account_box),
                  hintText: "input your username here",
                  contentPadding: EdgeInsets.fromLTRB(8, 0, 8, 0),
                  label: Text("Username"),
                  border: OutlineInputBorder(
                      borderSide: BorderSide(
                          color: Colors.black,
                          width: 2.0,
                          style: BorderStyle.solid)),
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.fromLTRB(0, 10, 0, 0),
              child: TextField(
                autofocus: true,
                obscureText: !showPwd,
                onChanged: onChangePassword,
                decoration: InputDecoration(
                  icon: const Icon(Icons.lock),
                  suffixIcon: InkWell(
                    onTap: () {
                      setState(() {
                        showPwd = !showPwd;
                      });
                    },
                    child: showPwd
                        ? const Icon(Icons.visibility)
                        : const Icon(Icons.visibility_off),
                  ),
                  hintText: "input your password here",
                  contentPadding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
                  label: const Text("Password"),
                  border: const OutlineInputBorder(
                      borderSide: BorderSide(
                          color: Colors.black,
                          width: 2.0,
                          style: BorderStyle.solid)),
                ),
              ),
            ),
            Align(
                alignment: Alignment.centerLeft,
                child: Row(
                  children: [
                    TextButton(
                        onPressed: () {
                          forgetPassword();
                        },
                        child: const Text("Forget Password?")),
                    const Text("/"),
                    TextButton(
                        onPressed: () {
                          createAccount();
                        },
                        child: const Text("Create an account")),
                  ],
                )),
            Container(
                width: 0.5 * MediaQuery.of(context).size.width,
                height: 44,
                margin: const EdgeInsets.fromLTRB(0, 20, 0, 0),
                decoration: const BoxDecoration(
                    color: Colors.red,
                    borderRadius: BorderRadius.all(Radius.circular(8))),
                child: TextButton(
                    onPressed: () {
                      onPressed();
                    },
                    child: const Text(
                      "Login",
                      style: TextStyle(color: Colors.white),
                    )))
          ]),
        )));
  }
}
